<template>
	<view class="bg-light">
	<!-- 	<tabsTop tabName="申请退款"></tabsTop> -->
		<!-- 商品信息 -->
		<view v-for="(item,index) in good.children">
			<view :key="index" class="bg-white flex justify-between py-2">
				<image style="width: 150rpx;height: 150rpx;"  class="mx-2 flex-shrink"
					:src="Domain_IMG+item.Picture_URL"></image>
				<view class="fout">{{item.Article_Name}}</view>
				<view style="margin-top: 40px;" class="mx-1 flex-shrink">
					<view class="fout-sm">&times;{{item.Quantity}}</view>
				</view>
			</view>	
		</view>
		<!-- 售后方式/退款原因 -->
		<view class="bg-white py-1">
			<picker :range="items1" range-key="value" class="font" @change="changeRefundMessage($event)" style="width: 100%; ">
				<view class="mx-2 flex justify-between align-center">
					<text>售后方式</text>
					<view>
						<text class="mr-2" :class="RefundMessage?'text-dark':'text-muted'">{{RefundMessage?RefundMessage:'请选择'}}</text>
						<uni-icons type="right" color="#828d96" size="16"></uni-icons>
					</view>
				</view>
			</picker>
			<picker :range="items" range-key="value" class="font mt-2" @change="changeRefundCause($event)" style="width: 100%; ">
				<view class="mx-2 flex justify-between">
					<text>退款原因</text>
					<view>
						<text class="mr-2" :class="RefundCause?'text-dark':'text-muted'">{{RefundCause?RefundCause:'请选择'}}</text>
						<uni-icons type="right" color="#828d96" size="16"></uni-icons>
					</view>
				</view>
			</picker>
		</view>
		<!-- 退款金额 -->
		<view class="bg-white py-1 font">
			<view class="mx-2 flex align-center ">
				<text>退款金额</text>
				<view>
					<text class="ml-2">￥{{good.children[0].Sales_Unit_Price}}</text>
				</view>
			</view>
		</view>
		<!-- 最多可退 -->
		<view class="m-2" style="font-size: 12px;">
			最多可退￥{{good.children[0].Sales_Unit_Price}}(含运费0.00)，退款将返还实际支付金额。
		</view>
		<!-- 手机号/退款说明/凭证 -->
		<view class="bg-white mb-4 font">
			<view class="flex mx-2 py-1">
				<text>手机号码</text>
				<view class="ml-2">{{good.children[0].Sales_Phone}}</view>
			</view>
			<view class="flex mx-2 py-1">
				<text class="flex-shrink">退款说明</text>
				<input v-model="refundExplanation" class="ml-2 w-100" type="text" placeholder="可选填退款说明" />
			</view>
			<view class="flex mx-2 py-1">
				<view class="upload-text mr-1">上传凭证</view>
				<view class="flex flex-wrap mb-2" style="width: 78%;">
					<view v-for="(image, index) in uploadedImages" :key="index" class="image-container"
						style="position: relative;">
						<image :src="image.base64Image" class="uploaded-image"></image>
						<view class="delete-icon" @click="deleteImage(index)">&times;</view>
					</view>
					<view class="flex justify-center align-center"
						style="width: 80px;height: 80px;background-color: #f7f8fa;">
						<uni-icons @click="chooseAndUploadImage" fontFamily='iconfont' color="#dcdddf"
							size="20">{{'\ue9f3'}}</uni-icons>
					</view>
				</view>
			</view>
		</view>
		<!-- 提交 -->
		<view class="fixed-bottom flex justify-center bg-white align-center">
			<button class="but" @click="submit()">提交</button>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import tabsTop from "@/components/tabs/tabs-top.vue";
	import {
		getJsonInquiry,
		getJson,
		FileList
	} from "@/api/global.js"
	import {
		getRefund,
		getRefundType,
		getWeChatRefundAction
	} from "@/api/orders.js"
	import {
		NowTime
	} from "@/static/js/DateUtil.js"
	import {accAdd} from "@/static/js/GeneralUtil.js"
	export default {
		components: {
			tabsTop, //顶部标题组件
		},
		data() {
			return {
				good: {},
				items: [],
				items1: [],
				Domain_IMG: app.globalData.Domain_IMG,
				Domain_Icon: "/static/icon",
				RefundCause:'',
				RefundMessage:'',
				refundExplanation: '', // 用户输入的退款说明
				base64Image: '',
				uploadedImages: [], // 存储已上传的图片的 base64 字符串数组
				refund_info:{//退款表
					Refund_SerialNumber:'',
					Collection_SerialNumber:'',
					Submit_Date:'',
					Refund_Date:'',
					Sales_Amount:0,
					Refund_Amount:0,
					Collection_Amount:0,
					Refund_Message:'',
					Children:{
						refund_detail:[]
					}
				},
				
			}
		},
		onLoad(options) {
			this.good = JSON.parse(decodeURIComponent(options.good));
			this.getJsonData('hmgx/refundReason.json');
			this.getJsonData1('hmgx/refund.json')
		},
		methods: {
			getRowStatus(status) {
				switch (status) {
					case '1':
						return "未发货";
					case '6':
						return "已发货";
					case '7':
						return "已发货";
					case '9':
						return "未发货";
					default:
						return "";
				}
			},
			getStatus(status) {
				switch (status) {
					case '1':
						return "仅退款";
					case '6':
						return "退货退款";
					case '7':
						return "退货退款";
					case '9':
						return "仅退款";
					default:
						return "";
				}
			},
			changeRefundMessage(e){//选择售后方式
				this.RefundMessage = this.items1[e.detail.value].value
			},
			changeRefundCause(e){//选择退款原因
				this.RefundCause = this.items[e.detail.value].value
			},
			async submit() {
				if(this.RefundCause == '' || this.RefundMessage == ''){
					uni.showToast({
						title: '请选择售后方式或退款原因',
						duration: 2000,
						icon:"error"
					})
				} else {
					if (!this.loading) {
						this.loading = true;
						uni.showLoading({
							title: "加载中..."
						});
						//形成json结构
						this.refund_info.Collection_SerialNumber = this.good.Collection_SerialNumber;
						this.refund_info.Submit_Date = NowTime();
						this.refund_info.Collection_Amount = this.good.Collection_Amount;
						this.refund_info.Refund_Message = this.RefundMessage;
						this.good.children.forEach(item=>{
							let Children = {
								refund_detail_pic:[]
							};
							this.uploadedImages.forEach(ite=>{
								Children.refund_detail_pic.push({
									Refund_Detail_Pic_SerialNumber:'',
									Refund_Detail_SerialNumber:'',
									Picture_URL:ite.Picture_URL,
								})
							})
							this.refund_info.Children.refund_detail.push({
								Refund_Detail_SerialNumber:'',
								Refund_SerialNumber:'',
								Sales_Order_Detail_SerialNumber:item.Sales_Order_Detail_SerialNumber,
								mchnt_order_no:this.good.mchnt_order_no,
								Refund_Cause:this.RefundCause,
								Refund_Explain:this.refundExplanation,
								Amount:item.Sales_Amount,
								Refund_Amount:item.Sales_Amount,
								Collection_Type:this.good.Collection_Type,
								Children
							})
							this.refund_info.Sales_Amount = accAdd(this.refund_info.Sales_Amount,item.Sales_Amount);
						})
						const res = await getWeChatRefundAction({
							Data:JSON.stringify({refund_info:[this.refund_info]}),
							Open_ID:app.globalData.Open_ID
						})
						if(res.Status == 'success'){
							uni.navigateTo({
								url: `/pages/my/refundDetails?Sales_Order_SerialNumber=${this.good.children[0].Sales_Order_SerialNumber}&Sales_Order_Detail_SerialNumber=${this.good.children[0].Sales_Order_Detail_SerialNumber}`
							});
						}else{
							uni.showToast({
								title: res.Cause,
								duration: 2000,
								icon:"error"
							})
						}
						uni.hideLoading();
						this.loading = false;
						// this.uploadedImages.forEach(item => {
						// 	larr_Pic.push(item.Picture_Url)
						// })
						// const res1 = await getRefundType({
						// 	Sales_Order_SerialNumber:this.good.children[0].Sales_Order_SerialNumber
						// })
						// if(res1.status == 0 && res1.data == "0"){
						// 	console.log('this.good.children',this.good.children);
						// 	const res = await getRefund({
						// 		Sales_Order_SerialNumber: this.good.children[0].Sales_Order_SerialNumber,
						// 		refund_detail_pic: JSON.stringify(larr_Pic),
						// 		Refund_Cause: JSON.stringify(this.selectedValue[0].text),
						// 		Refund_Explain: this.refundExplanation,
						// 		Refund_Message:JSON.stringify(this.selectedValue1[0].text),
						// 	})
						// 	if (res.Status == "success") {
						// 		console.log('res', res);
						// 		uni.navigateTo({
						// 			url: `/pages/my/refundDetails?Sales_Order_SerialNumber=${this.good.children[0].Sales_Order_SerialNumber}&Sales_Order_Detail_SerialNumber=${this.good.children[0].Sales_Order_Detail_SerialNumber}`
						// 		});
						// 	}
						// }else{
						// 	uni.showToast({
						// 		title: '已提交退款申请，无法再次提交',
						// 		duration: 2000,
						// 		icon:"error"
						// 	})
						// }
						// console.log('res1',res1);
						
					}
				}
				
			},
			async FileList(filePath, base64Image) {
				const res = await FileList({
					FileName: filePath,
					Data: base64Image,
					DataLength: '',
				})
				if (res.Status == "success") {
					this.uploadedImages.push({
						Picture_URl: res.Picture_Url,
						base64Image: base64Image
					});
				}else{
					uni.showToast({
						title: '上传失败',
						duration: 2000,
						icon: "error"
					})
				}
			},
			chooseAndUploadImage() {
				// 调用选择图片API
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						// tempFilePath可以作为img标签的src属性显示图片
						const tempFilePaths = res.tempFilePaths;
						if (tempFilePaths.length > 0) {
							this.convertImageToBase64(tempFilePaths[0]);
						}
					}
				});
			},
			convertImageToBase64(filePath) {
				const fileSystemManager = uni.getFileSystemManager();
				fileSystemManager.readFile({
					filePath: filePath,
					encoding: 'base64',
					success: (res) => {
						// console.log('222', res);
						const base64Image = 'data:image/png;base64,' + res.data;
						// 在这里处理你的base64字符串，例如保存到数据或状态，或者上传到服务器
						this.FileList(filePath, base64Image);
					},
					fail: (err) => {
						console.error('读取文件失败:', err);
					}
				});
			},
			deleteImage(index) {
				this.uploadedImages = this.uploadedImages.filter((item, i) => i != index)
			},
			async getJsonData(File) {
				const res = await getJsonInquiry({File})
				if (res.Status == "success") {
					this.items = JSON.parse(res.Data)
				}
			},
			async getJsonData1(File) {
				const res = await getJsonInquiry({File})
				if (res.Status == "success") {
					this.items1 = JSON.parse(res.Data)
				}
			},
		}
	}
</script>

<style>
	.fixed-bottom {
		position: fixed;
		bottom: 0;
		height: 50px;
		box-shadow: 2px 2px 4px rgb(0 0 0);
	}

	.but {
		width: 90%;
		height: 30px;
		font-size: 14px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 14px;
		color: white;
		background-color: #28a745;
	}

	.upload-text {
		width: 20%;
	}

	image {
		width: 80px;
		height: 80px;
	}

	.uploaded-image {
		width: 80px;
		height: 80px;
	}

	.image-container {
		position: relative;
		display: inline-block;
		margin-right: 10px;
		margin-bottom: 10px;
	}

	.delete-icon {
		position: absolute;
		top: 0;
		right: 0;
		background: rgba(0, 0, 0, 0.5);
		color: white;
		width: 30rpx;
		height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		border-radius: 50%;
		cursor: pointer;
	}
</style>